//
// Created by 17775 on 2024/10/31.
//

#include "LiveMode_Histogram.h"

LiveMode_Histogram::LiveMode_Histogram(int &docId) : _nDocIdLive(docId), histogramDataReceiveQueueObserver(new HistogramDataReceiveQueueObserver()) {

}

void LiveMode_Histogram::addHistogramDataReceiveListener(HistogramDataReceiveListener *listener) const {
    histogramDataReceiveQueueObserver->addListener(listener);
}

void LiveMode_Histogram::stopHistogramThread() {
    _isGettingNewHistogramData.store(false, std::memory_order_release);
    if(m_histogramThread.joinable()) {
        m_histogramThread.join();
    }
}

void LiveMode_Histogram::getData() {
    qDebug() << "getHistogramData";
    m_histogramThread = std::thread(&LiveMode_Histogram::getHistogramData, this);
}

void LiveMode_Histogram::getHistogramData() {
    while(_isGettingNewHistogramData.load(std::memory_order_acquire)) {
        bool _bHistogramValid = false;
        RayCi_LiveMode_Histogram_View_isValid(_nDocIdLive, &_bHistogramValid);
        if(_bHistogramValid) {
            int iDataLength = 0;
            RayCi_LiveMode_Histogram_getDataLength(_nDocIdLive, 8, &iDataLength);
            if(iDataLength != 0) {
                std::vector<float> dIntensityThresholds_buffer;
                std::vector<uint32_t> dCounts_buffer;
                dIntensityThresholds_buffer.resize(iDataLength);
                dCounts_buffer.resize(iDataLength);
                RayCi_LiveMode_Histogram_getDataAsBinary(_nDocIdLive, 8, false, &dIntensityThresholds_buffer[0], &iDataLength, &dCounts_buffer[0], &iDataLength);
                QVector<double> vecDoubleIntensityThresholds(dIntensityThresholds_buffer.begin(), dIntensityThresholds_buffer.end());
                QVector<double> percentageData;
                percentageData.resize(iDataLength);
                std::transform(dCounts_buffer.begin(), dCounts_buffer.end(), percentageData.begin(),
                               [](uint32_t value) {
                                   return static_cast<double>(value) / 41616;
                               });
                auto histogramData = std::make_shared<PowerProfileData<QVector<double>>>(vecDoubleIntensityThresholds, percentageData);
                histogramDataReceiveQueueObserver->put(std::move(histogramData));
            }
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

void LiveMode_Histogram::closeHistogramWindow() const {
    RayCi_LiveMode_Histogram_Window_close(_nDocIdLive);
}

LiveMode_Histogram::~LiveMode_Histogram() {
    _isGettingNewHistogramData.store(false, std::memory_order_release);
    if(m_histogramThread.joinable()) {
        m_histogramThread.join();
    }
    histogramDataReceiveQueueObserver->interrupt();
    histogramDataReceiveQueueObserver = nullptr;
}